<template>
  <div>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索和添加 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入搜索姓名" class="input-with-select" v-model="queryInfo.username" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddUser">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userList" border stripe>
        <el-table-column label="ID" prop="id"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="性别" prop="sex"></el-table-column>
        <el-table-column label="职务" prop="title"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="状态">
          <!-- 自定义列模板，使用作用域插槽，通过scope.row获取当前行的数据 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.status" active-value="Y" inactive-value='N' @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button> -->
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNo"
        :page-sizes="[5, 10, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="110px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="addForm.sex" label="男">男</el-radio>
          <el-radio v-model="addForm.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="职务" prop="mobile">
          <el-input v-model="addForm.title"></el-input>
        </el-form-item>
        <el-form-item label="企业微信Id" prop="title">
          <el-input v-model="editForm.wxid"></el-input>
        </el-form-item>
        <el-form-item label="发送短信验证" prop="sendMobileCode">
          <el-switch v-model="addForm.sendMobileCode" active-color="#13ce66"
                     inactive-color="#ff4949" active-value="Y" inactive-value="N"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="110px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="editForm.sex" label="男">男</el-radio>
          <el-radio v-model="editForm.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
         <el-form-item label="职务" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="企业微信Id" prop="title">
          <el-input v-model="editForm.wxid"></el-input>
        </el-form-item>
        <el-form-item label="发送短信验证" prop="sendMobileCode">
          <el-switch v-model="editForm.sendMobileCode" active-color="#13ce66"
                     inactive-color="#ff4949" active-value="Y" inactive-value="N"></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配权限" :visible.sync="roleDialogVisible" width="50%" @close="setRoleDialogClosed" height="60%">
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>
          <el-tree
                  :data="menuTreeList"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :default-checked-keys="selectedMenuIdList"
                  ref="menuTreeListRef"
                  highlight-current
                  :props="defaultProps">
          </el-tree>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveMenuList">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Api from '@/api/Api.js'
import Util from '@/libs/utils'
export default {
  data() {
    return {
      // 查询用户列表的参数对象
      queryInfo: {
        username: '',
        pageNo: 1, // 页码
        pageSize: 20, // 页大小
      },
      // 用户列表数据
      userList: [],
      allUserList: [],
      // 总记录数
      total: 0,
      // 添加对话框的显示或隐藏
      addDialogVisible: false,
      // 添加用户的表单数据对象
      addForm: {
        username: '',
        email: '',
        mobile: '',
        sex:'男',
        'sendMobileCode':'N'
      },
      // 添加用户的校验规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
            message: '邮箱格式不正确',
            trigger: 'blur',
          },
        ],
        mobile:[{required: true, message: '请输入手机号', trigger: 'blur'}, {
          validator: Util.validatePhone,
          trigger: 'blur'
        }],
      },
      // 修改对话框的显示或隐藏
      editDialogVisible: false,
      editForm: {
      'sendMobileCode':'N'
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
            message: '邮箱格式不正确',
            trigger: 'blur',
          },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
             pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
            message: '手机号格式不正确',
            trigger: 'blur',
          },
        ],
      },
      roleDialogVisible: false,
      userInfo: {},
      selectedMenuIdList:[],
      menuTreeList:[],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    showAddUser() {
      this.addDialogVisible = true;
      this.getAllUserList();
    },
    getUserList() {
        Api.getUserList(this.queryInfo).then(res => {
            if (res.success) {
                this.userList = res.data.records;
                this.total = res.data.total;
            } else {
                return this.$message.error('获取用户列表失败')
            }
        })
    },
    getAllUserList(curUserId) {
        Api.getAllUserList(this.queryInfo).then(res => {
            if (res.success) {
                this.allUserList = res.data;
                //this.allUserList = this.allUserList.filter((item,index)=>item.id != curUserId);
            } else {
                return this.$message.error('获取用户列表失败')
            }
        })
    },
    // 监听pagesize改变的事件
    handleSizeChange(pageSize) {
      this.queryInfo.pageSize = pageSize
      this.getUserList()
    },
    // 监听pagenum的事件
    handleCurrentChange(pageNo) {
      this.queryInfo.pageNo = pageNo
      this.getUserList()
    },
    // 监听 switch 开关状态的改变
    async userStateChange(userinfo) {
      Api.updateUserStatus({'id':userinfo.id, 'status':userinfo.status}).then(res => {
          if (res.success) {
              this.$message.success('更新用户状态成功！')
          } else {
              userinfo.status = (userinfo.status=='Y'?'N':'Y')
              return this.$message.error('更新用户状态失败！')
          }
      })
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        Api.saveOrUpdateUser(this.addForm).then(res => {
            if (res.success) {
              this.addDialogVisible = false
              this.getUserList()
              this.$message.success('添加用户成功')
            } else {
                return this.$message.error('更新用户状态失败: ' + res.msg)
            }
        })
      })
    },
    // 显示编辑用户对话框
    async showEditDialog(id) {
      Api.getUserDetail({'id':id}).then(res => {
            if (res.success) {
              this.editForm = res.data
              this.editDialogVisible = true
            } else {
              return this.$message.error('查询用户失败')
            }
        })
    },
    // 修改用户
    editUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return
        }
        Api.saveOrUpdateUser(this.editForm).then(res => {
            if (res.success) {
              this.editDialogVisible = false
              this.getUserList()
              this.$message.success('修改用户成功！')
            } else {
                return this.$message.error('修改用户失败: ' + res.msg)
            }
        })
      })
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 根据ID删除用户
    removeUserById(id) {
      this.$confirm('确定要删除该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${id}`)
          if (res.meta.status !== 200) {
            return this.$message.error('删除用户失败')
          }
          this.getUserList()
          this.$message.success('删除用户成功！')
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 显示分配角色的对话框
    async showRoleDialog(userInfo) {
      this.userInfo = userInfo;
      this.selectedMenuIdList = [];
      Api.menuListTree({userId:this.userInfo.id}).then(res =>{
        if(res.success){
          this.menuTreeList = res.data.menuList;
          this.selectedMenuIdList = res.data.selectIdList;
        }else{
          this.$message.error('加钱权限失败');
        }
        this.roleDialogVisible = true
      });

    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed() {
      this.userInfo = {}
      this.menuTreeList = [];
      this.selectedMenuIdList = [];
    },
    // 分配权限
    saveMenuList() {
      // 判断是否选择角色
      var menuIdArray = this.$refs.menuTreeListRef.getCheckedKeys();
      console.log(menuIdArray)
      Api.userMenuSet({menuIdList:menuIdArray,userId:this.userInfo.id}).then(res =>{
        if(res.success){
          this.getUserList();
          this.roleDialogVisible = false;
        }else{
          this.$message.error('加载权限失败');
        }
      });
    },
  },
}
</script>

<style lang="less" scoped>
</style>
